#include <QCoreApplication>
#include "common.h"
#include "DataProcessor.h"
#include "MulticastReceiver.h"
#include "MulticastSender.h"

#include <QObject>
#include <QTimer>
#include <iostream>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // 定义组播地址、端口和接口
    const std::string interface     = ETHERNET_INTERFACE;
    const std::string groupAddr     = MULTICAST_IPADDR;
    const u16         groupRecvPort = MULTICAST_RECV_PORT;
    const u16         groupSendPort = MULTICAST_SEND_PORT;

    // 创建 MulticastSender 实例，用于处理要发送的数据
    MulticastSender sender(groupAddr, groupSendPort);
    if (!sender.initSocket(interface))
    {
        std::cerr << "Failed to initialize MulticastSender" << std::endl;
        return 1;
    }

    // 创建一个 DataProcessor 实例，用于处理接收到的数据
    DataProcessor processor(sender);

    // 创建 MulticastReceiver 实例，传入 DataProcessor 对象
    MulticastReceiver receiver(groupAddr, groupRecvPort, interface);

    // 建立信号和槽的连接
    QObject::connect(&receiver, &MulticastReceiver::dataReceived,
                     &processor, &DataProcessor::onDataReceived);

    QObject::connect(&processor, &DataProcessor::sendDataToMulticast,
                     &sender, &MulticastSender::sendToMulticastGroup);

    // 启动接收数据的线程
    if (receiver.startReceiving())
    {
        std::cout << "Started receiving multicast messages on " << groupAddr << ":" << groupRecvPort
                  << " using interface " << interface << std::endl;
    }
    else
    {
        std::cerr << "Failed to start receiving multicast messages." << std::endl;
        return 1;
    }

    // 模拟运行 10 分钟，等待接收线程处理数据
    std::cout << "Main thread is running. Waiting for data to be processed..." << std::endl;

    // 使用 QTimer 设置 10 分钟后退出程序
    QTimer::singleShot(std::chrono::minutes(10).count() * 60 * 1000, &a, &QCoreApplication::quit);

    // 连接退出信号
    QObject::connect(&a, &QCoreApplication::aboutToQuit, [&]() {
        std::cout << "Program is exiting." << std::endl;
    });


    return a.exec();
}
